﻿using System;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using Devv.Core.Crypto;
using Devv.Core.UniDataTier;
using Devv.Core.Utils;

namespace BikeBouncer.BusinessLayer.Entities
{
	[DataContract, Serializable]
	public class User : BaseEntity
	{
		#region Properties

		[DataMember]
		public String Email { get; set; }

		[DataMember]
		public String DisplayName { get; set; }

		[DataMember]
		public Address Address { get; set; }

		#endregion

		#region Internal use only properties

		public String Password { get; set; }
		public String PasswordHash { get; set; }
		public DateTime RegDate { get; set; }
		public DateTime LoginDate { get; set; }

		#endregion

		#region Constructor

		public User()
		{
			Address = new Address();
		}

		public User(Int32 id)
		{
			Construct(DataAccess.User_Get(id));
		}

		public User(String email)
		{
			Construct(DataAccess.User_Get(email));
		}

		public User(SqlDataReader reader)
		{
			Construct(reader);
		}

		#endregion

		#region Loading

		public override void Load(SqlDataReader reader)
		{
			Id = DataHandler.GetInt32(reader, "UserId");
			Email = DataHandler.GetString(reader, "UserEmail");
			PasswordHash = DataHandler.GetString(reader, "UserPasswordHash");
			DisplayName = DataHandler.GetString(reader, "UserDisplayName");
			RegDate = DataHandler.GetDateTime(reader, "UserRegDate");
			LoginDate = DataHandler.GetDateTime(reader, "UserLoginDate");
			Active = DataHandler.GetBoolean(reader, "UserActive");

			Address = new Address();
			Address.Id = DataHandler.GetInt32(reader, "AddressId");

			if (Address.Id > 0)
			{
				Address.Load(reader);
			}
		}

		#endregion

		#region Helper methods

		public static String GetPasswordHash(String email, String password)
		{
			return Hash.SHA256(email.ToLower() + "|" + password);
		}

		public static String EmailToActivationKey(String email)
		{
			return Cipher.DESEncrypt(email, ConfigUtil.GetConfig("BikeBouncer.SecurityKeys.UserActivation"), true);
		}

		public static String ActivationKeyToEmail(String key)
		{
			try
			{
				return Cipher.DESDecrypt(key, ConfigUtil.GetConfig("BikeBouncer.SecurityKeys.UserActivation"), true);
			}
			catch (Exception ex)
			{
				ErrorManager.Log(ex, "Could not decrypt activation key.");

				return String.Empty;
			}
		}

		#endregion

		#region ToString

		public new String ToString()
		{
			if (!String.IsNullOrEmpty(DisplayName))
			{
				return DisplayName;
			}

			return Email;
		}

		#endregion
	}
}